package com.xpp.yanbi.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolExecutorConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        // 创建线程工厂
        ThreadFactory threadFactory = new ThreadFactory() {

            // 记录线程数
            int count = 1;

            @Override
            public Thread newThread(@NotNull Runnable r) {
                // 创建一个新线程，并将 runnable 传入
                Thread thread = new Thread(r);
                // 给线程设置一个名称
                thread.setName("线程" + count);
                // 线程数+1
                count++;
                // 返回线程
                return thread;
            }
        };
        // 创建一个线程池，线程池的核心线程大小为 2 ，最大线程数为4
        // 非核心线程空闲时间为100秒，任务队列为阻塞队列，长度为 4
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4,
                100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), threadFactory);
        return threadPoolExecutor;
    }
}
